<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm border-b border-gray-200 fixed top-0 left-0 right-0 z-30">
      <div class="flex items-center justify-between h-24 px-8">
        <div class="flex items-center gap-4">
          <div class="logo-icon w-12 h-12">
            <svg viewBox="0 0 100 100" fill="none">
              <circle cx="50" cy="50" r="45" stroke="url(#gradient1)" stroke-width="3" fill="none" />
              <circle cx="50" cy="50" r="35" stroke="url(#gradient2)" stroke-width="2" fill="none" />
              <path d="M30 40 L50 30 L70 40 L70 60 L50 70 L30 60 Z" fill="url(#gradient3)" opacity="0.8" />
              <circle cx="50" cy="50" r="8" fill="white" />
              <defs>
                <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#4A90E2" />
                  <stop offset="100%" style="stop-color:#7BB3F0" />
                </linearGradient>
                <linearGradient id="gradient2" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#5BA0F2" />
                  <stop offset="100%" style="stop-color:#8CC8FF" />
                </linearGradient>
                <linearGradient id="gradient3" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#4A90E2" />
                  <stop offset="100%" style="stop-color:#6BB0FF" />
                </linearGradient>
              </defs>
            </svg>
          </div>
          <div class="flex flex-col">
            <span class="text-xl font-bold text-blue-600">
              EduLiveLink管理系统
            </span>
            <span class="text-xs text-black">
              智能教育平台
            </span>
          </div>
        </div>
        <div class="flex items-center gap-4">
          <button class="bg-blue-600 text-white px-6 py-2 rounded-md font-medium hover:bg-blue-700 transition-colors"
            @click="goHome">返回首页</button>
        </div>
      </div>
    </nav>

    <!-- 上方空白区域 -->
    <div class="h-24 bg-white"></div>

    <!-- 主要内容区域 -->
    <div class="flex flex-1">
      <!-- 侧边栏 -->
      <aside class="w-64 bg-white shadow-sm border-r border-gray-200 fixed h-[calc(100vh-6rem)] z-40">
        <div class="p-6">
          <h2 class="text-lg font-semibold text-gray-900 mb-6">控制台导航</h2>
          <ul class="space-y-1">
            <li>
              <router-link to="/console"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath === '/console' ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                    <polyline points="9 22 9 12 15 12 15 22"></polyline>
                  </svg>
                </span>
                <span>控制台首页</span>
              </router-link>
            </li>
            <li>
              <router-link to="/console/usermanagement"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath.startsWith('/console/usermanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                    <circle cx="8.5" cy="7" r="4"></circle>
                    <line x1="20" y1="8" x2="20" y2="14"></line>
                    <line x1="23" y1="11" x2="17" y2="11"></line>
                  </svg>
                </span>
                <span>用户管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/console/classmanagement"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath.startsWith('/console/classmanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                    <polyline points="9 22 9 12 15 12 15 22"></polyline>
                  </svg>
                </span>
                <span>班级管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/console/coursemanagement"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath.startsWith('/console/coursemanagement') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path>
                    <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path>
                  </svg>
                </span>
                <span>课程管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/console/resources"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath.startsWith('/console/resources') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                    <polyline points="14 2 14 8 20 8"></polyline>
                    <line x1="16" y1="13" x2="8" y2="13"></line>
                    <line x1="16" y1="17" x2="8" y2="17"></line>
                    <polyline points="10 9 9 9 8 9"></polyline>
                  </svg>
                </span>
                <span>资源管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/console/settings"
                class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors"
                :class="currentPath.startsWith('/console/settings') ? 'bg-blue-50 text-blue-600' : 'text-gray-700'">
                <span class="w-5 h-5 flex items-center justify-center">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="3"></circle>
                    <path
                      d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z">
                    </path>
                  </svg>
                </span>
                <span>系统设置</span>
              </router-link>
            </li>
          </ul>
        </div>
      </aside>

      <!-- 主内容区 -->
      <main class="flex-1 ml-64 p-6">
        <div class="page-header">
          <h1 class="text-3xl font-bold text-gray-900 mb-2">课程管理</h1>
          <p class="page-description">管理平台所有课程信息，包括查看、新增、编辑和删除课程</p>
        </div>
        <div class="h-6"></div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
          <!-- 搜索区域 -->
          <div class="p-4 border-b border-gray-200">
            <div class="flex flex-wrap gap-4">
              <el-input v-model="searchKeyword" placeholder="搜索课程名称或教师姓名" style="width: 300px"
                clearable @clear="handleSearch" @keyup.enter="handleSearch" />
              <el-input v-model="searchTeacherName" placeholder="搜索教师姓名" style="width: 200px"
                clearable @clear="handleSearch" @keyup.enter="handleSearch" />
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="success" @click="showAddDialog">新增课程</el-button>
            </div>
          </div>

          <!-- 表格区域 -->
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程名称</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">教师ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">教师姓名</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">班级ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">星期</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间段</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="course in courseList" :key="course.id" class="hover:bg-gray-50">
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.id }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.courseName }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.teacherId }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.teacherName }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.classId }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.weekdayStr }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.timePeriodStr }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ formatDate(course.createTime) }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button class="text-blue-600 hover:text-blue-900 mr-4" @click="editCourse(course)">编辑</button>
                    <button class="text-red-600 hover:text-red-900" @click="deleteCourse(course)">删除</button>
                  </td>
                </tr>
                <tr v-if="courseList.length === 0 && !loading">
                  <td colspan="9" class="px-6 py-12 text-center text-gray-500">暂无课程数据</td>
                </tr>
                <tr v-if="loading">
                  <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                    <el-loading-spinner></el-loading-spinner>
                    <span class="ml-2">加载中...</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
            <div class="text-sm text-gray-700">共 {{ total }} 条记录</div>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
              :total="total" layout="prev, pager, next, sizes" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </div>
      </main>
    </div>

    <!-- 新增/编辑课程弹窗 -->
    <el-dialog v-model="showCourseDialog" :title="editingCourse ? '编辑课程' : '新增课程'" width="600px">
      <el-form ref="courseFormRef" :model="courseForm" :rules="courseFormRules" label-width="100px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="教师ID" prop="teacherId">
          <el-input v-model.number="courseForm.teacherId" placeholder="请输入教师ID" />
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input v-model="courseForm.teacherName" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model.number="courseForm.classId" placeholder="请输入班级ID" />
        </el-form-item>
        <el-form-item label="星期几" prop="weekday">
          <el-select v-model="courseForm.weekday" placeholder="请选择星期几">
            <el-option v-for="day in weekdays" :key="day.value" :label="day.label" :value="day.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间段" prop="timePeriod">
          <el-select v-model="courseForm.timePeriod" placeholder="请选择时间段">
            <el-option label="上午" :value="1" />
            <el-option label="下午" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCourseDialog = false">取消</el-button>
        <el-button type="primary" @click="submitCourseForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="确认删除" width="400px">
      <p>确定要删除课程 "{{ deletingCourse?.courseName }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { courseAPI } from '@/api/course.js'

// 路由相关
const route = useRoute()
const router = useRouter()
const currentPath = ref('')

// 返回首页方法
const goHome = () => {
  router.push('/')
}

// 响应式数据
const courseList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const searchTeacherName = ref('')
const loading = ref(false)

// 弹窗相关
const showCourseDialog = ref(false)
const showDeleteDialog = ref(false)
const editingCourse = ref(null)
const deletingCourse = ref(null)
const courseFormRef = ref(null)

// 星期选项
const weekdays = [
  { value: 1, label: '周一' },
  { value: 2, label: '周二' },
  { value: 3, label: '周三' },
  { value: 4, label: '周四' },
  { value: 5, label: '周五' },
  { value: 6, label: '周六' }
]

// 表单数据
const courseForm = reactive({
  id: null,
  courseName: '',
  teacherId: null,
  teacherName: '',
  classId: null,
  weekday: null,
  timePeriod: null
})

// 表单验证规则
const courseFormRules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { max: 50, message: '课程名称不能超过50个字符', trigger: 'blur' }
  ],
  teacherId: [
    { required: true, message: '请输入教师ID', trigger: 'blur' },
    { type: 'number', message: '教师ID必须是数字', trigger: 'blur' }
  ],
  teacherName: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' },
    { max: 50, message: '教师姓名不能超过50个字符', trigger: 'blur' }
  ],
  classId: [
    { required: true, message: '请输入班级ID', trigger: 'blur' },
    { type: 'number', message: '班级ID必须是数字', trigger: 'blur' }
  ],
  weekday: [
    { required: true, message: '请选择星期几', trigger: 'change' }
  ],
  timePeriod: [
    { required: true, message: '请选择时间段', trigger: 'change' }
  ]
}

// 页面加载时获取课程列表
onMounted(() => {
  fetchCourseList()
})

// 获取课程列表
const fetchCourseList = async () => {
  try {
    loading.value = true
    const params = {
      keyword: searchKeyword.value,
      teacherName: searchTeacherName.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 使用 POST 方法调用 API
    const response = await courseAPI.getCourses(params)
    
    if (response.code === 0) {
      courseList.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.msg || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    if (error.code === 'ERR_NETWORK') {
      ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
    } else {
      ElMessage.error('获取课程列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  searchTeacherName.value = ''
  currentPage.value = 1
  fetchCourseList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCourseList()
}

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchCourseList()
}

// 显示新增对话框
const showAddDialog = () => {
  editingCourse.value = null
  // 重置表单
  Object.assign(courseForm, {
    id: null,
    courseName: '',
    teacherId: null,
    teacherName: '',
    classId: null,
    weekday: null,
    timePeriod: null
  })
  showCourseDialog.value = true
}

// 编辑课程
const editCourse = async (item) => {
  try {
    // 获取课程详细信息
    const response = await courseAPI.getCourseById(item.id)
    if (response.code === 0) {
      editingCourse.value = response.data
      Object.assign(courseForm, {
        id: response.data.id,
        courseName: response.data.courseName,
        teacherId: response.data.teacherId,
        teacherName: response.data.teacherName,
        classId: response.data.classId,
        weekday: response.data.weekday,
        timePeriod: response.data.timePeriod
      })
      showCourseDialog.value = true
    } else {
      ElMessage.error(response.msg || '获取课程详情失败')
    }
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败，请稍后重试')
  }
}

// 删除课程
const deleteCourse = (item) => {
  deletingCourse.value = item
  showDeleteDialog.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    const response = await courseAPI.deleteCourse(deletingCourse.value.id)
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      showDeleteDialog.value = false
      fetchCourseList() // 重新加载列表
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除课程失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 提交表单
const submitCourseForm = async () => {
  if (!courseFormRef.value) return

  try {
    await courseFormRef.value.validate()
    
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '处理中...'
    })

    let response
    if (editingCourse.value) {
      // 编辑课程
      response = await courseAPI.updateCourse(courseForm)
    } else {
      // 新增课程
      response = await courseAPI.addCourse(courseForm)
    }
    
    loadingInstance.close()
    
    if (response.code === 0) {
      ElMessage.success(editingCourse.value ? '课程更新成功' : '课程新增成功')
      showCourseDialog.value = false
      fetchCourseList() // 重新加载列表
    } else {
      ElMessage.error(response.msg || (editingCourse.value ? '课程更新失败' : '课程新增失败'))
    }
  } catch (error) {
    console.error('保存课程失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  currentPath.value = newPath
}, { immediate: true })
</script>

<style scoped>
.page-header {
  margin-bottom: 1.5rem;
}

.page-description {
  color: #6b7280;
  font-size: 1rem;
}
</style>
